package com.nanbei.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/26 15:22
 */
public class CompletableFutureAPIDemo4 {
    public static void main(String[] args) {

        // applyToEither 比较两个线程谁的计算快,谁快就用谁的计算结果
        // thenCombine 等到两个异步线程计算结束后，处理两个异步线程的结果

        CompletableFuture<String> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("playA come in ...");
            // A玩家计算结果需要的时间
            try {
                TimeUnit.MILLISECONDS.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playA";
        });

        CompletableFuture<String> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("playB come in ...");
            // B玩家计算结果需要的时间
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playB";
        });

        // f 为异步线程计算较快的结果
        /*CompletableFuture<String> stringCompletableFuture = playA.applyToEither(playB, f -> f);
        System.out.println(stringCompletableFuture.join());*/

        CompletableFuture<String> result = playA.thenCombine(playB, (aResult, bResult) -> {
            System.out.println("对两个异步结果进行才处理");
            return aResult + " " + bResult;
        });
        System.out.println(result.join());

    }
}
